package cn.lzx.hrm.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class DefaultOAuth2FeignRequestInterceptor implements RequestInterceptor {

    Logger logger = LoggerFactory.getLogger(DefaultOAuth2FeignRequestInterceptor.class);

    //传入token请求头key
    private static final String TOKEN_HEADER_KEY = "Authorization";

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //获取ServletRequest属性
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //从requestAttributes获取请求对象
        HttpServletRequest request = requestAttributes.getRequest();

        //从请求对象中就可以获取token请求头
        String token = request.getHeader(TOKEN_HEADER_KEY);

        if (!StringUtils.isEmpty(token)){
            //通过requestTemplate设置请求头携带给下一个服务
            requestTemplate.header(TOKEN_HEADER_KEY,token);
            logger.error(" set token to next server!jjfjfjjjjjjjjjjjjjjjjjjjjjjjjjjj");
        }else{
            logger.error("token is null!jjfjfjjjjjjjjjjjjjjjjjjjjjjjjjjj");
        }

    }
}
